package com.mimose.cosy.proxy.api;

import com.mimose.cosy.lang.Objs;
import com.mimose.cosy.proxy.enums.ProxyType;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.annotation.Nonnull;
import java.lang.reflect.Method;

/**
 * @author mimose
 * @description cglib proxy api
 * @date 2021/4/24
 */
public abstract class CglibProxy implements MethodInterceptor, IProxy {

    private Object proxyTarget;

    public CglibProxy() {
    }

    @Override
    public ProxyType proxyType() {
        return ProxyType.CGLIB;
    }

    @Override
    public Object wrap(@Nonnull Object proxyTarget) {
        Objs.requireNonNull(proxyTarget, "Cglib Proxy fail, the target is null");
        newProxy(proxyTarget);
        this.proxyTarget = proxyTarget;

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.proxyTarget.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        try {
            // do before
            beforeInvoke(method, args);
            // process
            final Object result = method.invoke(this.proxyTarget, args);
            // do after
            afterInvoke(result, method, args);
            return result;
        } catch (Exception e) {
            // do after throw exception
            afterThrowing(e, method, args);
            throw e;
        }
    }

    /**
     * initialization
     * @param proxyTarget
     * @return
     */
    public abstract CglibProxy newProxy(@Nonnull Object proxyTarget);
}
